<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="热搜ID" prop="topicId">
        <el-input
          v-model="queryParams.topicId"
          placeholder="请输入热搜主题ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入文章标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- 添加创建时间搜索 -->
      <el-form-item label="创建时间" prop="createdTime">
        <el-date-picker
          v-model="queryParams.createdTime"
          type="date"
          placeholder="选择创建时间"
          value-format="YYYY-MM-DD"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['article:article:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['article:article:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['article:article:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Upload"
          @click="handleUploadWord"
          style="cursor: pointer;"
        >上传Word文档</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="热搜主题ID" align="center" prop="topicId" width="100" />
      <el-table-column label="文章标题" align="center" prop="title" width="300" show-overflow-tooltip />
      <el-table-column label="文章内容" align="center" prop="content" width="150" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.content ? scope.row.content.replace(/<[^>]+>/g, '').slice(0, 200) + (scope.row.content.replace(/<[^>]+>/g, '').length > 100 ? '...' : '') : '' }}
        </template>
      </el-table-column>
      <!-- 修改来源URL列，添加复制按钮 -->
      <el-table-column label="来源URL" align="center" prop="sourceUrl" width="250" show-overflow-tooltip>
        <template #default="scope">
          <div class="url-container">
            <span class="url-text">{{ scope.row.sourceUrl }}</span>
            <el-button 
              type="primary" 
              size="small" 
              icon="DocumentCopy" 
              @click="copyUrl(scope.row.sourceUrl)"
              class="copy-btn"
              title="复制链接"
            >
            </el-button>
          </div>
        </template>
      </el-table-column>
      <!-- 修改时间显示格式为 YYYY-MM-DD -->
      <el-table-column label="创建时间" align="center" prop="createdTime" width="120">
        <template #default="scope">
          <span>{{ formatDate(scope.row.createdTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="showArticleDetail(scope.row)">查看详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['article:article:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['article:article:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文章内容对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="articleRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="热搜主题ID" prop="topicId">
          <el-input v-model="form.topicId" placeholder="请输入热搜主题ID" :disabled="form.id != null" />
        </el-form-item>
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="文章内容">
          <editor v-model="form.content" :min-height="300" />
        </el-form-item>
        <el-form-item label="来源URL" prop="sourceUrl">
          <el-input v-model="form.sourceUrl" placeholder="请输入来源URL" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 文章详情对话框 -->
    <el-dialog
      title="文章详情"
      v-model="detailOpen"
      width="800px"
      append-to-body
      destroy-on-close
    >
      <div class="article-detail">
        <h2 class="article-title">{{ currentArticle.title }}</h2>
        <div class="article-meta">
          <span>热搜主题ID: {{ currentArticle.topicId }}</span>
          <span>创建时间: {{ formatDate(currentArticle.createdTime) }}</span>
          <span>来源: <a :href="currentArticle.sourceUrl" target="_blank">{{ currentArticle.sourceUrl }}</a></span>
        </div>
        <el-divider />
        <div class="article-content" v-html="currentArticle.content"></div>
      </div>
    </el-dialog>

    <!-- Word文档上传对话框 -->
    <el-dialog
      title="上传Word文档"
      v-model="uploadDialogVisible"
      width="600px"
      append-to-body
      destroy-on-close
    >
      <el-form ref="uploadFormRef" :model="uploadForm" :rules="uploadRules" label-width="100px">
        <el-form-item label="热搜主题ID" prop="topicId">
          <el-input v-model="uploadForm.topicId" placeholder="请输入热搜主题ID" />
        </el-form-item>
        <el-form-item label="Word文档" prop="file">
          <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".doc,.docx"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            drag
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 .doc/.docx 文件，且不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="来源URL" prop="sourceUrl">
          <el-input v-model="uploadForm.sourceUrl" placeholder="请输入来源URL（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitUpload" :loading="uploadLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Article">
import { listArticle, getArticle, delArticle, addArticle, updateArticle, uploadWordDocument } from "@/api/article/article";
import { parseTime } from "@/utils/ruoyi"; // 确保导入时间格式化工具
import { UploadFilled } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();

const articleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 文章详情相关状态
const detailOpen = ref(false);
const currentArticle = ref({
  title: '',
  content: '',
  sourceUrl: '',
  topicId: '',
  createdTime: ''
});

// Word文档上传相关状态
const uploadDialogVisible = ref(false);
const uploadLoading = ref(false);
const fileList = ref([]);
const uploadForm = ref({
  topicId: '',
  sourceUrl: ''
});
const uploadRules = {
  topicId: [
    { required: true, message: "热搜主题ID不能为空", trigger: "blur" }
  ]
};

// 新增日期格式化函数 - 只显示年月日
function formatDate(dateString) {
  if (!dateString) return '';
  return dateString.split(' ')[0]; // 直接截取日期部分
}

// 复制URL功能
function copyUrl(url) {
  if (!url) {
    proxy.$modal.msgWarning("URL为空，无法复制");
    return;
  }
  
  // 使用现代浏览器的 Clipboard API
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(url).then(() => {
      proxy.$modal.msgSuccess("链接已复制到剪贴板");
    }).catch((err) => {
      console.error('复制失败:', err);
      // 降级到传统方法
      fallbackCopy(url);
    });
  } else {
    // 降级到传统复制方法
    fallbackCopy(url);
  }
}

// 传统复制方法（兼容性更好）
function fallbackCopy(text) {
  const textArea = document.createElement('textarea');
  textArea.value = text;
  textArea.style.position = 'fixed';
  textArea.style.left = '-999999px';
  textArea.style.top = '-999999px';
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();
  
  try {
    const successful = document.execCommand('copy');
    if (successful) {
      proxy.$modal.msgSuccess("链接已复制到剪贴板");
    } else {
      proxy.$modal.msgError("复制失败，请手动复制");
    }
  } catch (err) {
    console.error('复制失败:', err);
    proxy.$modal.msgError("复制失败，请手动复制");
  } finally {
    document.body.removeChild(textArea);
  }
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    topicId: null,
    title: null,
    createdTime: null, 
  },
  rules: {
    topicId: [
      { required: true, message: "热搜主题ID不能为空", trigger: "blur" }
    ],
    title: [
      { required: true, message: "文章标题不能为空", trigger: "blur" }
    ],
    sourceUrl: [
      { required: true, message: "来源URL不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询文章内容列表 */
function getList() {
  loading.value = true;
  listArticle(queryParams.value).then(response => {
    articleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    topicId: null,
    title: null,
    content: null,
    sourceUrl: null,
    delFlag: null
  };
  proxy.resetForm("articleRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加文章";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getArticle(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改文章";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["articleRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateArticle(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addArticle(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除选中的文章？').then(function() {
    return delArticle(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

// 显示文章详情
function showArticleDetail(row) {
  currentArticle.value = row;
  detailOpen.value = true;
}

/** 打开Word文档上传对话框 */
function handleUploadWord() {
  console.log('handleUploadWord 被调用');
  
  // 先获取下一个可用的topicId
  getNextTopicId().then(response => {
    if (response.code === 200) {
      uploadForm.value = {
        topicId: response.data.toString(),
        sourceUrl: ''
      };
    } else {
      proxy.$modal.msgError("获取topicId失败: " + response.msg);
      return;
    }
  }).catch(error => {
    proxy.$modal.msgError("获取topicId失败: " + (error.message || "未知错误"));
    return;
  });
  
  uploadDialogVisible.value = true;
  fileList.value = [];
}

/** 文件选择变化处理 */
function handleFileChange(file) {
  // 检查文件大小（10MB）
  const isLt10M = file.raw.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    proxy.$modal.msgError('上传文件大小不能超过 10MB!');
    fileList.value = [];
    return;
  }
  
  // 检查文件格式
  const isValidFormat = file.name.toLowerCase().endsWith('.doc') || file.name.toLowerCase().endsWith('.docx');
  if (!isValidFormat) {
    proxy.$modal.msgError('只能上传 .doc/.docx 格式的文件!');
    fileList.value = [];
    return;
  }
  
  fileList.value = [file];
}

/** 文件移除处理 */
function handleFileRemove() {
  fileList.value = [];
}

/** 提交Word文档上传 */
function submitUpload() {
  proxy.$refs["uploadFormRef"].validate(valid => {
    if (valid) {
      if (fileList.value.length === 0) {
        proxy.$modal.msgError('请选择要上传的Word文档');
        return;
      }
      
      uploadLoading.value = true;
      
      const formData = new FormData();
      formData.append('file', fileList.value[0].raw);
      formData.append('topicId', uploadForm.value.topicId);
      if (uploadForm.value.sourceUrl) {
        formData.append('sourceUrl', uploadForm.value.sourceUrl);
      }
      
      uploadWordDocument(formData).then(response => {
        proxy.$modal.msgSuccess("Word文档上传并解析成功");
        uploadDialogVisible.value = false;
        getList(); // 刷新列表
      }).catch(error => {
        proxy.$modal.msgError("上传失败: " + (error.message || "未知错误"));
      }).finally(() => {
        uploadLoading.value = false;
      });
    }
  });
}

getList();
</script>

<style scoped>
.article-detail {
  padding: 20px;
}

.article-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
}

.article-meta {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
  gap: 10px;
}

.article-content {
  line-height: 1.8;
  font-size: 16px;
  text-align: left;
}

/* 新增URL容器样式 */
.url-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.url-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.copy-btn {
  flex-shrink: 0;
  padding: 4px 8px;
  font-size: 12px;
}
</style>